import sys
import os

import xbmcgui
import xbmcaddon

import hck_scraper
import tmr_queens_scraper

Addon = sys.modules['__main__'].Addon
#enable localization
getLS = Addon.getLocalizedString

#TODO: Remove the debug prints
#TODO: Add extra scrapers
#TODO: Find a way to bypass the xbmc cache
#TODO: Exceptions should display a message on screen
#TODO: autorefresh images if on photos
#TODO: Remove the working gif from relevant pages
#TODO: Package!
class GUI(xbmcgui.WindowXML):
    #Label Controls
    CONTROL_MAIN_IMAGE = 100
    CONTROL_USAGE_TEXT = 103
    #Label Actions
    ACTION_CONTEXT_MENU = [117]
    ACTION_MENU = [122]
    ACTION_PREVIOUS_MENU = [9,10]
    ACTION_SHOW_INFO = [11]
    ACTION_EXIT_SCRIPT = [13]
    ACTION_DOWN = [4]
    ACTION_UP = [3]

    ACTIVESOURCE = 0

    SOURCES = list()
    SOURCES.append({'name': 'Home.co.ke Cameras', 'object': None,
                    'lib':'hck_scraper', 'url':
                    'http://home.co.ke/index.php/traffic-cameras'})
    SOURCES.append({'name': 'TMR Queens.au Cameras', 'object': None,
                    'lib':"tmr_queens_scraper", 'url':
                    'http://www.tmr.qld.gov.au/Traffic-cameras-by-location.aspx'})

    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXML.__init__(self, *args, **kwargs)
        self.city_iconpath = "special://home/addons/script.image.trafficcamera/resources/skins/default/media/city-1290032361.png"
        self.location_iconpath = "special://home/addons/script.image.trafficcamera/resources/skins/default/media/leftover_bacon_Camera_Lens.png"
        #Make sure we have a cache dir
        self.CACHE_PATH = "special://profile/addons/script.image.trafficcamera/cache/"
        if not os.path.exists(self.CACHE_PATH): os.makedirs(self.CACHE_PATH)
            #self.hck = hck_scraper.Scrape(self.SOURCES[0]['url'], self.CACHE_PATH)
        for SRC in self.SOURCES:
            SRC['object'] = eval(SRC["lib"]).Scrape(SRC["url"],
                                                   self.CACHE_PATH)

        self.IDX = 0

    def setScraper(self):
        if self.IDX > len(self.SOURCES) or self.IDX < 0:
            self.IDX = 0
        self.SCRAPER = self.SOURCES[self.IDX]['object']
        # Fetch the html for the service
        self.SCRAPER.init_tree()
        self.showCities()

    def onInit(self):
        self.getControl(102).setLabel(getLS(32001)) #fixme
        self.showServices()

    def onFocus(self, controlId):
        pass

    def onAction(self, action):
        print "Action: ",action.getButtonCode(),":",action.getId()
        if action in self.ACTION_MENU:
            print "+++ action menu:"
        elif action in self.ACTION_UP:
            print "+++ action up:"
            self.IDX+=1
            self.setScraper()
        elif action in self.ACTION_DOWN:
            print "+++ action down:"
            self.IDX-=1
            self.setScraper()
        elif action in self.ACTION_SHOW_INFO:
            print "+++ show info menu:"
            self.toggleInfo()
        elif action in self.ACTION_CONTEXT_MENU:
            print "+++ context menu:"
            self.download()
        elif action in self.ACTION_PREVIOUS_MENU:
            print "+++ previous menu:"
            # exit the script
            if self.getProperty('type') == 'services':
                self.close()
            elif self.getProperty('type') == 'cities':
                self.showServices()
            elif self.getProperty('type') == 'locations':
                self.showCities()
            # return to city
            elif self.getProperty('type') == 'photo':
                self.showLocations(self.current_city)
        elif action in self.ACTION_EXIT_SCRIPT:
            print "+++ exit menu:"
            self.close()

    def onClick(self, controlId):
        if controlId == self.CONTROL_MAIN_IMAGE:
            if self.getProperty('type') == 'services':
                unclean_str = self.getLabel()
                clean_str = unclean_str.split("\n")[1].split(" (")[0]
                print "Cleaned string to", clean_str
                print "original was",unclean_str
                self.IDX = self.resolveService(clean_str)
                self.setScraper()
            elif self.getProperty('type') == 'cities':
                unclean_str = self.getLabel()
                clean_str = unclean_str.split("\n")[1].split(" (")[0]
                print "Cleaned string to", clean_str
                self.current_city = clean_str
                self.showLocations(self.current_city)
            elif self.getProperty('type') == 'locations':
                # Strip out extra lines added by Showitems
                unclean_str = self.getLabel()
                clean_str = unclean_str.split("\n")[1].split(" (")[0]
                print "Cleaned string to", clean_str
                self.current_location = clean_str
                self.showPhotos(self.current_location)
            elif self.getProperty('type') == 'photo':
                self.toggleInfo()

    def getProperty(self, property, controlId=CONTROL_MAIN_IMAGE):
        """Returns a property of the selected item"""
        return self.getControl(controlId).getSelectedItem().getProperty(property)

    #TODO - Add label support
    def getLabel(self, controlId=CONTROL_MAIN_IMAGE):
        """Returns a property of the selected item"""
        return self.getControl(controlId).getSelectedItem().getLabel()

    def toggleInfo(self):
        selectedControl = self.getControl(self.CONTROL_MAIN_IMAGE)
        if self.getProperty('showInfo') == 'false':
            for i in range(selectedControl.size()):
                selectedControl.getListItem(i).setProperty('showInfo', 'true')
                self.getControl(self.CONTROL_USAGE_TEXT).setVisible(True)
        else:
            for i in range(selectedControl.size()):
                selectedControl.getListItem(i).setProperty('showInfo', 'false')
                self.getControl(self.CONTROL_USAGE_TEXT).setVisible(False)

    def showServices(self):
        print "Starting showServices"
        self.getControl(self.CONTROL_USAGE_TEXT).setText('\n'.join([getLS(32040), getLS(32041), getLS(32042)]))
        self.getControl(self.CONTROL_USAGE_TEXT).setVisible(False)
        self.getControl(self.CONTROL_MAIN_IMAGE).reset() #This is necessary when returning from cities.
        services = []
        for src in self.SOURCES:
            services.append(
                {'pic':self.city_iconpath, 
                 'description':'Camera for %s' % src['name'],
                 'title':src['name']})
        print "got services ", services
        self.showItems(services, 'services')
    
    def resolveService(self, svc_name):
        """Resolves the service index given a service description"""
        idx = 0
        for src in self.SOURCES:
            if src['name'] == svc_name:
                return idx
            idx += 1
        #Nothing, select the first service
        return 0


    def showPhotos(self, location): #the order is significant!
        print "Starting Showphotos"
        self.getControl(self.CONTROL_MAIN_IMAGE).reset() #Clear city list.
        self.getControl(self.CONTROL_USAGE_TEXT).setVisible(False)
        photo = self.SCRAPER.getImages(location) # Get a list of photos from the link.
        print "got photos ",photo
        self.showItems(photo, 'photo')

    def showLocations(self, city):
        print "Starting Showlocations"
        self.getControl(self.CONTROL_MAIN_IMAGE).reset() #This is necessary when returning from photos.
        self.getControl(self.CONTROL_USAGE_TEXT).setVisible(False)
        locations = self.SCRAPER.getLocations(city)
        print "got locations ",locations
        for idx in range(len(locations)):
            locations[idx]['pic'] = self.location_iconpath
        self.showItems(locations, 'locations')

    def showCities(self):
        print "Starting showcities"
        self.getControl(self.CONTROL_USAGE_TEXT).setText('\n'.join([getLS(32040), getLS(32041), getLS(32042)]))
        self.getControl(self.CONTROL_USAGE_TEXT).setVisible(False)
        self.getControl(self.CONTROL_MAIN_IMAGE).reset() #This is necessary when returning from photos.
        cities = self.SCRAPER.getCities()
        for idx in range(len(cities)):
                cities[idx]['pic'] = self.city_iconpath
        print "got cities ",cities
        self.showItems(cities, 'cities')


    def showItems(self, itemSet, type):
        total = len(itemSet)
        for i, item in enumerate(itemSet):
            item['showInfo'] = 'true'
            item['type'] = type
            item['title'] = self.SOURCES[self.ACTIVESOURCE]['name'] + '\n' + item['title'] + ' (%s/%s)' % (i+1, total)
            self.addListItem(self.CONTROL_MAIN_IMAGE, item)

    def addListItem(self, controlId, properties):
        #print properties
        li = xbmcgui.ListItem(label=properties['title'], label2=properties['description'], iconImage=properties['pic'])
        for p in properties.keys():
            li.setProperty(p, properties[p])
        self.getControl(controlId).addItem(li)
